import React from "react";
import {Input, Space as AntdSpace} from 'antd';
import {VJsonComponent} from "../../factory";
import {YvanEvent} from "../../types";
import {apply, YvanEventBind, YvanEventDispatch} from "../../utils/helper";
import * as Extend from '../../extend'
import {FormItemBaseState, FormItemBaseProp, VJsonFormItemBase} from "./VJsonFormItemBase";
import {Field, ImportResult, readExcelWithFieldSet, RowValidateObject} from '../../xlsx'
import _ from "lodash";
import {toJS} from "mobx";
import {clearLoading, loading} from "../notify";

export interface ExcelImportVJsonProp extends FormItemBaseProp<ExcelImport> {
    addonAfter?: string | React.ReactNode
    addonBefore?: string | React.ReactNode
    defaultValue?: string
    disabled?: boolean
    maxLength?: number
    prefix?: string | React.ReactNode
    size?: 'large' | 'middle' | 'small'
    suffix?: string | React.ReactNode
    type?: string
    onChange?: YvanEvent<ExcelImport>
    onPressEnter?: YvanEvent<ExcelImport>
    onInput?: YvanEvent<ExcelImport>
    allowClear?: boolean
    bordered?: boolean
    className?:string
}

export interface ExcelImportState extends FormItemBaseState<ExcelImport> {

}

@VJsonComponent({
    view: 'excelImport'
})
export default class ExcelImport extends VJsonFormItemBase<ExcelImport, ExcelImportVJsonProp, ExcelImportState> {
    static defaultProps = {
        ...VJsonFormItemBase.defaultProps,
        dataStartRow: 2,
        titleRowNumber: 1,
        allowClear: true,
    }

    constructor(props: any) {
        super(props, ExcelImport.defaultProps);
    }

    private _rowValidate(rv: RowValidateObject) {
        return YvanEventDispatch(this.props.vjson.rowValidate, this, rv);
    }

    private _otherValidate(importResult: ImportResult, resolve: (value?: (ImportResult | PromiseLike<ImportResult> | undefined)) => void) {
        return YvanEventDispatch(this.props.vjson.afterClientValidate, this, importResult, resolve);
    }

    private _fieldValidate(fields: Field[], columnTitles: string[]):boolean {
        return YvanEventDispatch(this.props.vjson.fieldValidate, this, fields, columnTitles);
    }

    protected onValueChange(file: any) {

        loading("文件载入中...")
        if (file && file.target && file.target.files[0]) {
            this.value = file.target.files[0]
            readExcelWithFieldSet(file.target.files[0], this.props.vjson.fields,
                this.props.vjson.dataStartRow,
                this.props.vjson.titleRowNumber,
                this.props.vjson.rowValidate?this._rowValidate.bind(this):undefined,
                this.props.vjson.afterClientValidate?this._otherValidate.bind(this):undefined,
                this.props.vjson.fieldValidate?this._fieldValidate.bind(this):undefined).then(result => {
                YvanEventDispatch(this.props.vjson.onChange, this, result, true)
            })
        } else {
            this.value = null
            YvanEventDispatch(this.props.vjson.onChange, this, {allData: [], errorData: [], errorMsgData: [], okData: []}, false)
            clearLoading();
        }


    }

    public reOpen() {
        // @ts-ignore
        this.inputRef.current.input.value="";
        // @ts-ignore
        this.inputRef.current.setValue("",()=>{});
        // @ts-ignore
        this.inputRef.current.input.defaultValue=""
        YvanEventDispatch(this.props.vjson.onChange, this, {allData: [], errorData: [], errorMsgData: [], okData: []}, false)
        if(this.inputRef.current){
            // 模拟input点击事件
            var evt = new MouseEvent("click", {
                bubbles: false,
                cancelable: true,
                view: window
            });
            // @ts-ignore
            this.inputRef.current.input.dispatchEvent(evt)
        }
    }

    inputRef = React.createRef();

    protected renderWrapper(): JSX.Element {
        if (Extend.isDebugMode()) {
            console.log('RenderExcelImport ', this.toString())
        }

        return (
            //@ts-ignore
            <Input key={this.key} view_id={this.key} aria-roledescription={this.view} className="ant-file-wrapper" className={this.props.vjson.className+" ant-file-wrapper"}
                   // @ts-ignore
                   ref={this.inputRef}
                   style={apply(this, toJS(this.props.vjson.style))}
                   addonAfter={this.props.vjson.addonAfter}
                   addonBefore={this.props.vjson.addonBefore}
                   maxLength={this.props.vjson.maxLength}
                   prefix={this.props.vjson.prefix}
                   size={this.props.vjson.size}
                   suffix={this.props.vjson.suffix}
                   type={"file"}
                   bordered={this.props.vjson.bordered}
                   accept={".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"}
                   disabled={this.props.vjson.disabled}
                   allowClear={this.props.vjson.allowClear}
                   onChange={this.onValueChange.bind(this)}
                   onInput={YvanEventBind(this.props.vjson.onInput, this)}
                   onPressEnter={YvanEventBind(this.props.vjson.onPressEnter, this)}/>
        )
    }
}
